<template>
  <div class="table-container">
    <div class="flex justify-between mb10">
      <div>
        <el-button type="primary" @click="getData">获取数据</el-button> tips: 该表格为万条数据渲染示例
      </div>
      <div class="flex">
        <el-input-number v-model="line" class="mr10" :min="1" />
        <el-button type="primary" plain @click="scrollTable">滚动到第{{ line }}行</el-button>
      </div>
    </div>
    <div class="content">
      <virtual-scroll
        ref="virtualScroll"
        :data="tableData"
        :item-size="62"
        key-prop="id"
        @change="(renderData) => virtualList = renderData"
      >
        <el-table
          ref="trackListTable"
          :data="virtualList"
          style="width: 100%"
          :height="tableHeight"
          border
        >
          <el-table-column
            prop="id"
            label="ID"
            width="180"
          />
          <el-table-column
            prop="date"
            label="日期"
            width="180"
          />
          <el-table-column
            prop="name"
            label="姓名"
            width="180"
          />
          <el-table-column
            prop="address"
            label="地址"
          />
        </el-table>
      </virtual-scroll>
    </div>
  </div>
</template>

<script>
import VirtualScroll from 'el-table-virtual-scroll'

export default {
  components: {
    VirtualScroll
  },
  data() {
    return {
      tableHeight: 580,
      line: 1,
      virtualList: [],
      tableData: []
    }
  },
  created() {
    var screenHeight = document.documentElement.clientHeight
    console.log('当前屏幕高度为：' + screenHeight + '像素')
  },
  mounted() {
    window.addEventListener('resize', this.getNewTableHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.getNewTableHeight)
  },
  methods: {
    getNewTableHeight() {
      this.tableHeight = document.documentElement.clientHeight / (695 / 580)
    },
    // 滚动表格
    scrollTable() {
      if (this.tableData.length === 0) return this.$message.warning('请先获取数据')
      if (this.line > this.tableData.length) return this.$message.warning('超出数据范围')

      this.$refs.virtualScroll.scrollTo(this.line - 1)
    },
    getData() {
      const newTableData = []
      for (let index = 0; index < 10000; index++) {
        let address = ''
        if (index % 2 === 0) {
          address = '上海市普陀区金沙江路 1518 弄'
        } else {
          address = '上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄'
        }
        newTableData.push({
          id: index + 1,
          date: '2016-05-02',
          name: '王小虎',
          address
        })
      }
      this.tableData = newTableData
    }
  }
}
</script>

<style lang="scss" scoped>
.mr10 {
  margin-right: 10px;
}
.mb10 {
  margin-bottom: 10px;
}
.flex {
  display: flex;
}
.justify-between {
 justify-content: space-between;
}
</style>
